#region License

/*
  GShield - Game Shield
  Copyright (C) 2006-2007 WaveTech Digital Technologies, Inc.
                                http://www.wtdt.com

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#endregion License

#region Includes

using System;
using System.Configuration;
using System.Windows.Forms;
using WaveTech.GShield.Common;
using WaveTech.GShield.Data;
using WaveTech.GShield.Engine.Factories;
using WaveTech.GShield.Engine.Tools;
using WaveTech.GShield.Manager.Properties;

#endregion

namespace WaveTech.GShield.Manager
{
	public partial class Options : Form
	{
		private readonly Setting sys;

		#region Constructor

		public Options()
		{
			InitializeComponent();

			InitializeRequiredSystems();

			sys = SettingsDAO.Get();

			PopulateExclusionsList();
			PopulateExceptionsList();
			PopulateServicesList();
		}

		#endregion Constructor

		#region Options_Load

		private void Options_Load(object sender, EventArgs e)
		{
			m_bannerImage.Image = BannerFactory.CreateBanner(m_bannerImage.Width,
			                                                 m_bannerImage.Height, BannerFactory.BannerStyle.WinVistaBlack,
			                                                 Resources.B48x48_KCMSystem, "GShield Options",
			                                                 "Set the System Options for GShield");

			string[] lst = LpqDAO.GetAllQuestions().ToArray();
			cboQuestion1.Items.AddRange(lst);
			cboQuestion2.Items.AddRange(lst);

			cboQuestion1.SelectedItem = LpqDAO.GetQuestionById(sys.LPQ1Id);
			cboQuestion2.SelectedItem = LpqDAO.GetQuestionById(sys.LPQ2Id);
			txtAnswer1.Text = sys.LPQ1Ans;
			txtAnswer2.Text = sys.LPQ2Ans;

			txtEmailAddress.Text = sys.AdminEmail;
			txtSmtpLogin.Text = sys.SmtpLogin;
			txtSmtpPassword.Text = sys.SmtpPassword;
			txtSmtpServer.Text = sys.SmtpServer;

			if (sys.SmtpRequireLogin.HasValue)
				chkRequiredLogin.Checked = sys.SmtpRequireLogin.Value;

			if (chkRequiredLogin.Checked)
			{
				txtSmtpLogin.Enabled = true;
				txtSmtpPassword.Enabled = true;
			}
			else
			{
				txtSmtpLogin.Enabled = false;
				txtSmtpPassword.Enabled = false;
			}

			if (sys.UsageSleepTimer != null)
				txtUsageSleepTimer.Text = Time.MillisecondsToMinutes(int.Parse(sys.UsageSleepTimer)).ToString();

			if (sys.RatingsSleepTimer != null)
				txtRatingsSleepTimer.Text = Time.MillisecondsToMinutes(int.Parse(sys.RatingsSleepTimer)).ToString();

			if (sys.BannedSleepTimer != null)
				txtBannedSleepTimer.Text = Time.MillisecondsToMinutes(int.Parse(sys.BannedSleepTimer)).ToString();

			if (sys.TrimNonExactRatingResults != null)
				chkTrimNonExactRatingResults.Checked = sys.TrimNonExactRatingResults;
		}

		#endregion Options_Load

		#region Initial Required Systems

		private void InitializeRequiredSystems()
		{
		}

		#endregion Initial Required Systems

		#region Populate Exceptions List

		private void PopulateExceptionsList()
		{
			cboExceptions.Items.Clear();
			cboExceptions.Items.AddRange(ExceptionsDAO.GetAllExceptionNames().ToArray());
		}

		#endregion Populate Exceptions List

		#region Populate Services List

		private void PopulateServicesList()
		{
			lstWebServices.Items.Clear();
			lstWebServices.Items.AddRange(ServicesDAO.GetAllServiceUrls().ToArray());
		}

		#endregion Populate Services List

		#region Populate Exclusions List

		private void PopulateExclusionsList()
		{
			cboExclusions.Items.Clear();
			cboExclusions.Items.AddRange(DirectoryNameExclusionsDAO.GetAllDirectoryNameExclusions().ToArray());
		}

		#endregion Populate Exclusions List

		#region btnCancel_Click

		private void btnCancel_Click(object sender, EventArgs e)
		{
			Close();
		}

		#endregion btnCancel_Click

		#region btnOk_Click

		private void btnOk_Click(object sender, EventArgs e)
		{
			if (txtPassword1.Text != txtPassword2.Text)
			{
				MessageBox.Show("Your passwords do not match.", "GShield Setup", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			else if (txtPassword1.Text.Length > 0 && txtPassword1.Text.Length < 4)
			{
				MessageBox.Show("Your passwords should be at least 4 characters.", "GShield Setup", MessageBoxButtons.OK,
				                MessageBoxIcon.Error);
				return;
			}

			if (cboQuestion1.SelectedItem == null || cboQuestion2.SelectedItem == null)
			{
				MessageBox.Show("You must select some forgetten password questions.", "GShield Setup", MessageBoxButtons.OK,
				                MessageBoxIcon.Error);
				return;
			}
			else if (txtAnswer1.Text.Length <= 0 || txtAnswer2.Text.Length <= 0)
			{
				MessageBox.Show("You must supply forgetten password questions answers.", "GShield Setup", MessageBoxButtons.OK,
				                MessageBoxIcon.Error);
				return;
			}
			else if (cboQuestion1.SelectedItem == cboQuestion2.SelectedItem)
			{
				MessageBox.Show("You must select different forgetten password questions.", "GShield Setup", MessageBoxButtons.OK,
				                MessageBoxIcon.Error);
				return;
			}

			int result;
			if (txtBannedSleepTimer.Text.Trim().Length < 0)
			{
				MessageBox.Show("You must supply a Banned Sleep Timer value.", "GShield Setup", MessageBoxButtons.OK,
				                MessageBoxIcon.Error);
				return;
			}
			else if (int.TryParse(txtBannedSleepTimer.Text, out result) == false)
			{
				MessageBox.Show("You must supply a valid Banned Sleep Timer value, a whole number.", "GShield Setup",
				                MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}

			if (txtUsageSleepTimer.Text.Trim().Length < 0)
			{
				MessageBox.Show("You must supply a Usage Sleep Timer value.", "GShield Setup", MessageBoxButtons.OK,
				                MessageBoxIcon.Error);
				return;
			}
			else if (int.TryParse(txtUsageSleepTimer.Text, out result) == false)
			{
				MessageBox.Show("You must supply a valid Usage Sleep Timer value, a whole number.", "GShield Setup",
				                MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}

			if (txtRatingsSleepTimer.Text.Trim().Length < 0)
			{
				MessageBox.Show("You must supply a Ratings Sleep Timer value.", "GShield Setup", MessageBoxButtons.OK,
				                MessageBoxIcon.Error);
				return;
			}
			else if (int.TryParse(txtRatingsSleepTimer.Text, out result) == false)
			{
				MessageBox.Show("You must supply a valid Ratings Sleep Timer value, a whole number.", "GShield Setup",
				                MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}

			if (txtPassword2.Text.Length > 0)
				sys.AdminPassword = Hash.ComputeHash(txtPassword2.Text.Trim(), "SHA256", null);

			sys.AdminEmail = txtEmailAddress.Text;
			sys.LPQ1Id = LpqDAO.GetIdByQuestion(cboQuestion1.SelectedItem.ToString());
			sys.LPQ1Ans = txtAnswer1.Text;
			sys.LPQ2Id = LpqDAO.GetIdByQuestion(cboQuestion2.SelectedItem.ToString());
			sys.LPQ2Ans = txtAnswer2.Text;
			sys.SmtpServer = txtSmtpServer.Text;
			sys.SmtpRequireLogin = chkRequiredLogin.Checked;
			sys.SmtpLogin = txtSmtpLogin.Text;
			sys.SmtpPassword = txtSmtpPassword.Text;
			sys.RatingsSleepTimer = txtRatingsSleepTimer.Text;
			sys.UsageSleepTimer = txtUsageSleepTimer.Text;
			sys.BannedSleepTimer = txtBannedSleepTimer.Text;
			sys.TrimNonExactRatingResults = chkTrimNonExactRatingResults.Checked;

			SettingsDAO.Update(sys);

			Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

			config.AppSettings.Settings.Remove("UnhandledExceptionManager/EmailTo");
			config.AppSettings.Settings.Add("UnhandledExceptionManager/EmailTo", "gshielderrors@wtdt.com");

			config.AppSettings.Settings.Remove("UnhandledExceptionManager/DefaultDomain");
			config.AppSettings.Settings.Add("UnhandledExceptionManager/DefaultDomain", "wtdt.com");

			config.AppSettings.Settings.Remove("UnhandledExceptionManager/MailServer");
			config.AppSettings.Settings.Add("UnhandledExceptionManager/MailServer", sys.SmtpServer);

			config.AppSettings.Settings.Remove("UnhandledExceptionManager/MailServerPort");
			config.AppSettings.Settings.Add("UnhandledExceptionManager/MailServerPort", "25");

			config.AppSettings.Settings.Remove("UnhandledExceptionManager/MailServerUsername");
			config.AppSettings.Settings.Add("UnhandledExceptionManager/MailServerUsername", sys.SmtpLogin);

			config.AppSettings.Settings.Remove("UnhandledExceptionManager/MailServerPassword");
			config.AppSettings.Settings.Add("UnhandledExceptionManager/MailServerPassword", sys.SmtpPassword);

			config.Save(ConfigurationSaveMode.Modified);
			ConfigurationManager.RefreshSection("appSettings");

			Close();
		}

		#endregion btnOk_Click

		#region btnAddException_Click

		private void btnAddException_Click(object sender, EventArgs e)
		{
			if (txtExceptionsName.Text.Length > 0)
			{
				Cursor.Current = Cursors.WaitCursor;
				txtExceptionsName.Enabled = false;

				if (ExceptionsDAO.GetExceptionByName(txtExceptionsName.Text) == null)
				{
					ExceptionsDAO.Insert(txtExceptionsName.Text);

					Cursor.Current = Cursors.Default;
					MessageBox.Show("Successfully added " + txtExceptionsName.Text + " as an exception.", "Exception Add Successful",
					                MessageBoxButtons.OK, MessageBoxIcon.Information);
				}
				else
				{
					Cursor.Current = Cursors.Default;
					MessageBox.Show("Cannot add " + txtExceptionsName.Text + " as an exception, one already exists.",
					                "Exception Add Failure",
					                MessageBoxButtons.OK, MessageBoxIcon.Error);
				}

				PopulateExceptionsList();
				txtExceptionsName.Text = "";
			}
			else
			{
				Cursor.Current = Cursors.Default;
				MessageBox.Show("You must supply a program name to add an exception.", "Add Exception Failure",
				                MessageBoxButtons.OK, MessageBoxIcon.Error);
			}

			Cursor.Current = Cursors.Default;
			txtExceptionsName.Enabled = true;
		}

		#endregion btnAddException_Click

		#region btnRemoveException_Click

		private void btnRemoveException_Click(object sender, EventArgs e)
		{
			if (cboExceptions.SelectedItem != null && cboExceptions.SelectedItem.ToString().Length > 0)
			{
				Cursor.Current = Cursors.WaitCursor;
				cboExceptions.Enabled = false;

				ExceptionsDAO.Delete(cboExceptions.SelectedItem.ToString());

				Cursor.Current = Cursors.Default;
				MessageBox.Show("Successfully removed " + cboExceptions.SelectedItem + " as an exception.",
				                "Exception Remove Successful",
				                MessageBoxButtons.OK, MessageBoxIcon.Information);

				PopulateExceptionsList();
				cboExceptions.SelectedItem = "";
			}
			else
			{
				Cursor.Current = Cursors.Default;
				MessageBox.Show("You must select a program name to remove an exception.", "Remove Exception Failure",
				                MessageBoxButtons.OK, MessageBoxIcon.Error);
			}

			Cursor.Current = Cursors.Default;
			cboExceptions.Enabled = true;
		}

		#endregion btnRemoveException_Click

		#region btnAddWebService_Click

		private void btnAddWebService_Click(object sender, EventArgs e)
		{
			if (txtAddWebService.Text.Length > 0)
			{
				Cursor.Current = Cursors.WaitCursor;
				txtAddWebService.Enabled = false;

				ServicesDAO.Insert(txtAddWebService.Text);

				Cursor.Current = Cursors.Default;
				MessageBox.Show("Successfully added " + txtAddWebService.Text + " as a Advisor Web Service.",
				                "Web Service Add Successful",
				                MessageBoxButtons.OK, MessageBoxIcon.Information);

				PopulateServicesList();
				txtAddWebService.Text = "";
			}
			else
			{
				Cursor.Current = Cursors.Default;
				MessageBox.Show("You must supply a URL to add an Advisor Web Service.", "Add Web Service Failure",
				                MessageBoxButtons.OK, MessageBoxIcon.Error);
			}

			Cursor.Current = Cursors.Default;
			txtAddWebService.Enabled = true;
		}

		#endregion btnAddWebService_Click

		#region btnRemoveWebService_Click

		private void btnRemoveWebService_Click(object sender, EventArgs e)
		{
			if (lstWebServices.SelectedItem != null && lstWebServices.SelectedItem.ToString().Length > 0)
			{
				if (lstWebServices.Items.Count == 1)
				{
					if (
						MessageBox.Show(
							"You must have at least one Advisors Web Service for GShield to run correctly.\nIf you remove this last web service GShield will not be able to\nget any more ESRB ratings!",
							"Confirm Last Advisor Removal", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
					{
						Cursor.Current = Cursors.WaitCursor;
						lstWebServices.Enabled = false;

						ServicesDAO.Delete(lstWebServices.SelectedItem.ToString());

						Cursor.Current = Cursors.Default;
						MessageBox.Show("Successfully removed " + lstWebServices.SelectedItem + " as a Web Service.",
						                "Web Service Remove Successful",
						                MessageBoxButtons.OK, MessageBoxIcon.Information);

						PopulateServicesList();
						lstWebServices.SelectedItem = "";
					}
				}
				else
				{
					Cursor.Current = Cursors.WaitCursor;
					lstWebServices.Enabled = false;

					ServicesDAO.Delete(lstWebServices.SelectedItem.ToString());

					Cursor.Current = Cursors.Default;
					MessageBox.Show("Successfully removed " + lstWebServices.SelectedItem + " as a Web Service.",
					                "Web Service Remove Successful",
					                MessageBoxButtons.OK, MessageBoxIcon.Information);

					PopulateServicesList();
					lstWebServices.SelectedItem = "";
				}
			}
			else
			{
				Cursor.Current = Cursors.Default;
				MessageBox.Show("You must select a web service to remove.", "Remove Web Service Failure",
				                MessageBoxButtons.OK, MessageBoxIcon.Error);
			}

			Cursor.Current = Cursors.Default;
			lstWebServices.Enabled = true;
		}

		#endregion btnRemoveWebService_Click

		#region btnAddExclusion_Click

		private void btnAddExclusion_Click(object sender, EventArgs e)
		{
			if (txtExclusionToAdd.Text.Length > 0)
			{
				Cursor.Current = Cursors.WaitCursor;
				txtExclusionToAdd.Enabled = false;

				if (DirectoryNameExclusionsDAO.GetExclusionByName(txtExclusionToAdd.Text) == null)
				{
					DirectoryNameExclusionsDAO.Insert(txtExclusionToAdd.Text);

					Cursor.Current = Cursors.Default;
					MessageBox.Show("Successfully added " + txtExclusionToAdd.Text + " as a directory excusion.",
					                "Exclusion Add Successful",
					                MessageBoxButtons.OK, MessageBoxIcon.Information);
				}
				else
				{
					Cursor.Current = Cursors.Default;
					MessageBox.Show("Cannot add exlusion " + txtExclusionToAdd.Text + " as it already exists.",
					                "Exclusion Add Failed",
					                MessageBoxButtons.OK, MessageBoxIcon.Error);
				}

				PopulateExclusionsList();
				txtExclusionToAdd.Text = "";
			}
			else
			{
				Cursor.Current = Cursors.Default;
				MessageBox.Show("You must supply a directory name to add a directory exclusion.", "Add Exclusion Failure",
				                MessageBoxButtons.OK, MessageBoxIcon.Error);
			}

			Cursor.Current = Cursors.Default;
			txtExclusionToAdd.Enabled = true;
		}

		#endregion btnAddExclusion_Click

		#region btnRemoveExclusion_Click

		private void btnRemoveExclusion_Click(object sender, EventArgs e)
		{
			if (cboExclusions.SelectedItem != null && cboExclusions.SelectedItem.ToString().Length > 0)
			{
				Cursor.Current = Cursors.WaitCursor;
				cboExclusions.Enabled = false;

				DirectoryNameExclusionsDAO.Delete(cboExclusions.SelectedItem.ToString());

				Cursor.Current = Cursors.Default;
				MessageBox.Show("Successfully removed " + cboExclusions.SelectedItem + " as a directory exclusion.",
				                "Exclusion Remove Successful",
				                MessageBoxButtons.OK, MessageBoxIcon.Information);

				PopulateExclusionsList();
				cboExclusions.SelectedItem = "";
			}
			else
			{
				Cursor.Current = Cursors.Default;
				MessageBox.Show("You must select a directory name to remove a directory exclusion.", "Remove Exclusion Failure",
				                MessageBoxButtons.OK, MessageBoxIcon.Error);
			}

			Cursor.Current = Cursors.Default;
			cboExclusions.Enabled = true;
		}

		#endregion btnRemoveExclusion_Click
	}
}